package com.boomshake.service.impl;

import com.boomshake.mapper.CommissionRecordMapper;
import com.boomshake.mapper.DistributorRelationMapper;
import com.boomshake.service.DistributorService;
import com.boomshake.vo.CommissionDetailVO;
import com.boomshake.vo.DistributorStatisticsVO;
import com.boomshake.vo.DistributorTreeVO;
import com.boomshake.vo.DistributorVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 分销员服务实现类
 *
 * @author BoomShake
 * @date 2024-12-16
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DistributorServiceImpl implements DistributorService {

    private final DistributorRelationMapper distributorRelationMapper;
    private final CommissionRecordMapper commissionRecordMapper;

    @Override
    public List<DistributorTreeVO> getDistributorTree(Long storeId, Integer level, Integer status) {
        try {
            // 查询所有符合条件的分销员数据
            List<DistributorTreeVO> allDistributors = distributorRelationMapper.selectDistributorTreeData(storeId, level, status);
            
            // 构建树形结构
            return buildDistributorTree(allDistributors);
        } catch (Exception e) {
            log.error("获取分销员树形结构失败", e);
            throw new RuntimeException("获取分销员树形结构失败: " + e.getMessage());
        }
    }

    @Override
    public DistributorTreeVO getDistributorDetail(Long distributorId) {
        try {
            return distributorRelationMapper.selectDistributorDetail(distributorId);
        } catch (Exception e) {
            log.error("获取分销员详情失败, distributorId: {}", distributorId, e);
            throw new RuntimeException("获取分销员详情失败: " + e.getMessage());
        }
    }

    @Override
    public CommissionDetailVO getDistributorCommissionDetails(Long distributorId, Integer page, Integer size) {
        try {
            CommissionDetailVO result = new CommissionDetailVO();
            
            // 查询佣金汇总信息
            Map<String, BigDecimal> summaryMap = commissionRecordMapper.selectCommissionSummary(distributorId);
            CommissionDetailVO.CommissionSummary summary = new CommissionDetailVO.CommissionSummary()
                    .setTotalCommission(summaryMap.getOrDefault("totalCommission", BigDecimal.ZERO))
                    .setWithdrawnCommission(summaryMap.getOrDefault("withdrawnCommission", BigDecimal.ZERO))
                    .setPendingCommission(summaryMap.getOrDefault("pendingCommission", BigDecimal.ZERO));
            result.setCommissionSummary(summary);
            
            // 查询佣金记录列表（限制条数，用于详情展示）
            List<CommissionDetailVO.CommissionRecordItem> records = commissionRecordMapper.selectCommissionRecordsList(distributorId, size);
            result.setCommissionRecords(records);
            
            return result;
        } catch (Exception e) {
            log.error("获取分销员佣金明细失败, distributorId: {}", distributorId, e);
            throw new RuntimeException("获取分销员佣金明细失败: " + e.getMessage());
        }
    }

    @Override
    public boolean updateDistributorStatus(Long distributorId, Integer status) {
        try {
            int result = distributorRelationMapper.updateDistributorStatus(distributorId, status);
            return result > 0;
        } catch (Exception e) {
            log.error("更新分销员状态失败, distributorId: {}, status: {}", distributorId, status, e);
            throw new RuntimeException("更新分销员状态失败: " + e.getMessage());
        }
    }

    @Override
    public DistributorStatisticsVO getDistributorStatistics(Long storeId, Integer level, Integer status) {
        try {
            Map<String, Object> statisticsMap = distributorRelationMapper.selectDistributorStatistics(storeId, level, status);
            
            return new DistributorStatisticsVO()
                    .setTotalDistributors(getIntegerValue(statisticsMap, "totalDistributors"))
                    .setActiveDistributors(getIntegerValue(statisticsMap, "activeDistributors"))
                    .setInactiveDistributors(getIntegerValue(statisticsMap, "inactiveDistributors"))
                    .setLevel1Count(getIntegerValue(statisticsMap, "level1Count"))
                    .setLevel2Count(getIntegerValue(statisticsMap, "level2Count"))
                    .setLevel3Count(getIntegerValue(statisticsMap, "level3Count"))
                    .setTotalCommission(getBigDecimalValue(statisticsMap, "totalCommission"));
        } catch (Exception e) {
            log.error("获取分销员统计信息失败", e);
            throw new RuntimeException("获取分销员统计信息失败: " + e.getMessage());
        }
    }

    /**
     * 构建分销员树形结构
     * @param allDistributors 所有分销员数据
     * @return 树形结构列表
     */
    private List<DistributorTreeVO> buildDistributorTree(List<DistributorTreeVO> allDistributors) {
        // 按parent_id分组
        Map<Long, List<DistributorTreeVO>> parentMap = allDistributors.stream()
                .collect(Collectors.groupingBy(d -> d.getParentId() == null ? 0L : d.getParentId()));
        
        // 递归构建树形结构
        List<DistributorTreeVO> rootNodes = parentMap.getOrDefault(0L, new ArrayList<>());
        buildChildren(rootNodes, parentMap);
        
        return rootNodes;
    }

    /**
     * 递归构建子节点
     * @param nodes 当前节点列表
     * @param parentMap 父级映射
     */
    private void buildChildren(List<DistributorTreeVO> nodes, Map<Long, List<DistributorTreeVO>> parentMap) {
        for (DistributorTreeVO node : nodes) {
            List<DistributorTreeVO> children = parentMap.getOrDefault(node.getDistributorId(), new ArrayList<>());
            node.setChildren(children);
            if (!children.isEmpty()) {
                buildChildren(children, parentMap);
            }
        }
    }

    /**
     * 安全获取Integer值
     */
    private Integer getIntegerValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return 0;
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        return 0;
    }

    /**
     * 安全获取BigDecimal值
     */
    private BigDecimal getBigDecimalValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return BigDecimal.ZERO;
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof Number) {
            return BigDecimal.valueOf(((Number) value).doubleValue());
        }
        return BigDecimal.ZERO;
    }

    /**
     * 获取门店分销员列表
     * 
     * @param storeId 门店ID
     * @return 分销员列表
     */
    @Override
    public List<DistributorVO> getStoreDistributors(Long storeId) {
        if (storeId == null) {
            throw new IllegalArgumentException("门店ID不能为空");
        }
        
        // 调用Mapper查询门店分销员
        return distributorRelationMapper.getDistributorsByStoreId(storeId);
    }
} 